<template>
    <div class="main coupon-edit">
        <section>
            <el-form :model="formData" :rules="formRules" :disabled="type==='view'" size="medium" ref="form" label-width="150px">
                <div class="block-header"><div>设置拼团活动</div></div>
                <div class="block-content">
                    <el-form-item label="拼团类型:" prop="groupBookingType" :rules="commonRules.notNullRule">
                        <el-radio v-for="(value, key) in groupBookingTypeData" v-model="formData.groupBookingType" :key="key" :label="key">{{value}}</el-radio>
                    </el-form-item>
                   <el-form-item label="选择商品:" prop="goodsName" :rules="commonRules.notNullRule" class="groupBooking_goods">
                     <!-- <el-select>
                        <el-option>商品</el-option>
                        <el-option>套餐</el-option>
                      </el-select> -->
                      <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!!formData.goodsId" @click="chooseGoods" plain>添加商品</el-button>
                      <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!!formData.goodsId" @click="chooseGoodsPackage" plain>添加套餐</el-button>
                   </el-form-item>
                   <div class="use-type-block" v-if="formData.goodsId">
                      <div class="good-list" style="margin-top: 10px;">
                        <el-table :data="[formData]" border highlight-current-row>
                          <el-table-column align="center" width="300" label="ID" prop="goodsId"></el-table-column>
                          <el-table-column align="center" width="300" :label=" formData.goodsType === 2 ? '套餐名称' : '商品名称'" prop="goodsName"></el-table-column>
                          <el-table-column align="center" label="商品图片" width="300">
                            <template slot-scope="scope">
                              <img style="width: 200px" :src="formData.goodsPic">
                            </template>
                          </el-table-column>
                          <el-table-column align="center" label="操作" width="100">
                            <template slot-scope="scope">
                              <el-button type="danger" size="mini" :disabled="type==='edit'" @click="removeTempSelect(scope.row)">移除</el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                    <div class="use-type-block" v-if="tempPackageSelect.length">
                      <div class="good-list" style="margin-top: 10px;">
                        <el-table :data="tempPackageSelect" border highlight-current-row>
                          <el-table-column align="center" width="300" label="ID" prop="goods_id"></el-table-column>
                          <el-table-column align="center" width="300" label="套餐名称" prop="title"></el-table-column>
                          <el-table-column align="center" label="操作" width="100">
                              <template slot-scope="scope">
                                  <el-button type="danger" size="mini" @click="removeTempPackageSelect(scope.row)">移除</el-button>
                              </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                    <el-form-item label="商品类目:" v-if="formData.categoryName">
                      {{formData.categoryName}}
                    </el-form-item>
                    <el-form-item label="商品标题:" prop="goodsName" :rules="commonRules.notNullRule">
                      <el-input :disabled="type==='edit'" v-model="formData.goodsName" placeholder="请输入商品标题" ></el-input>
                    </el-form-item>
                    <el-form-item label="活动置顶:" prop="isTop" :rules="commonRules.notNullRule">
                      <el-switch
                        @change="show(formData)"
                        v-model="formData.isTop"
                        active-text="是"
                        inactive-text="否"
                        active-value=1
                        inactive-value=0
                      >
                      </el-switch>
                    </el-form-item>
                    <el-form-item label="活动名称:" prop="promotionName" :rules="commonRules.notNullRule">
                      <el-input v-model="formData.promotionName" placeholder="请输入活动名称" ></el-input>
                    </el-form-item>
                    <el-form-item label="生效时间：" prop="startTime" :rules="commonRules.notNullRule">
                      <el-date-picker
                        style="width: 250px;"
                        :disabled="type==='edit'"
                        v-model="formData.startTime"
                        type="datetime"
                        :picker-options="pickerOptions"
                        @focus="getCurrentTime"
                        :default-time="defaultStartHour"
                        placeholder="开始日期"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker>
                      至
                      <el-date-picker
                        style="width: 250px;"
                        v-model="formData.endTime"
                        type="datetime"
                        :picker-options="pickerOptions2"
                        placeholder="结束日期"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker>
                      <!-- <el-date-picker
                        v-model="formData.tempDateRange"
                        type="datetimerange"
                        range-separator="~"
                        :picker-options="pickerOptions"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker> -->
                    </el-form-item>
                   <el-form-item label="参团人数:" prop="groupNeedNum" :rules="commonRules.groupRule">
                        <el-input :disabled="type==='edit'" v-model="formData.groupNeedNum" placeholder="请输入具体参团人数 2~100的数字" ></el-input>
                    </el-form-item>
                    <el-form-item label="已拼件数:" prop="alreadyGroupGoodsNum">
                        <el-input :disabled="type==='edit'" v-model="formData.alreadyGroupGoodsNum" placeholder="请输入具体参团人数 2~100的数字" ></el-input>
                    </el-form-item>

                    <el-form-item label="拼团有效期:" prop="groupTime" :rules="commonRules.numberRule">
                      <div class="dateSelectDive">
                        <el-select :disabled="type==='edit'" v-model="durningDay" @change="setGroupTime">
                          <el-option
                            v-for="item in 31"
                            :key="item"
                            :label="item - 1"
                            :value="item - 1">
                          </el-option>
                        </el-select>
                        <span>日</span>
                        <el-select :disabled="type==='edit'" v-model="durningHour" @change="setGroupTime">
                          <el-option
                            v-for="item in 25"
                            :key="item"
                            :label="item - 1 "
                            :value="item - 1">
                          </el-option>
                        </el-select>
                        <span>时</span>
                        <el-select :disabled="type==='edit'" v-model="durningMinute" @change="setGroupTime">
                          <el-option
                            v-for="item in 61"
                            :key="item"
                            :label="item - 1"
                            :value="item - 1">
                          </el-option>
                        </el-select>
                        <span>分</span>
                      </div>
                    </el-form-item>
                    <el-form-item label="参团次数:" prop="groupLimit" :rules="commonRules.notNullRule" class="limit_el-form">
                        <!-- <el-checkbox>开启限购</el-checkbox> -->
                        <el-input v-model="formData.groupLimit" :disabled="type==='edit'">
                          <template slot="append">件/人</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="模拟成团:" prop="isOpenVirtualGroup">
                        <el-checkbox :disabled="type==='edit'" v-model="formData.isOpenVirtualGroup" true-label="1" false-label="0">模拟成团</el-checkbox>
                    </el-form-item>
                    <el-form-item label="优惠设置:">
                      <el-table v-show="formData.goodsPrice" :data="[formData]" border highlight-current-row>
                        <el-table-column align="center"  label="商品原价(元)" prop="goodsPrice"></el-table-column>
                        <el-table-column align="center" width="200"  label="拼团价（VIP/钻石/董事价格都一样）" prop="groupPrice">
                          <template slot-scope="scope">
                            <el-form-item prop="groupPrice" :rules="commonRules.priceRule">
                              <el-input :disabled="type==='edit'" v-model="formData.groupPrice" style="width: 180px" placeholder="请输入拼团价格" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>

                        <el-table-column align="center" width="200"  label="商品佣金(元)" prop="goodsCommission">
                          <template slot-scope="scope">
                            {{formData.goodsCommission ? formData.goodsCommission : 0}}
                          </template>
                        </el-table-column>

                        <el-table-column align="center" width="200"  label="拼团最高佣金" prop="commission">
                          <template slot-scope="scope">
                            <el-form-item prop="commission" :rules="formRules.commissionLimit">
                              <el-input :disabled="type==='edit'" v-model="formData.commission" style="width: 180px" placeholder="请输入拼团价格" ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>

                        <el-table-column align="center"  label="库存" prop="distributableSkuNumber"></el-table-column>
                      </el-table>
                    </el-form-item>
                    <el-form-item label="" v-if="type!=='view'">
                        <el-button type="primary" size="medium" :loading="btnLoading" @click="save">保存</el-button>
                        <el-button type="info" size="medium" plain @click="$router.push({ name: 'groupBooking' })">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <div v-if="type==='view'" style="margin-left: 150px">
                <el-button type="success" size="medium" @click="$router.push({ name: 'groupBooking' })">返回</el-button>
            </div>
        </section>
    </div>
</template>
<script>
  import {regexp} from '@/utils/tools'
  import { goodsCheck } from '@/api/activity/fullReduce'

  export default {
    name: 'groupBookingEdit',
    props: {
      id: { default: '' },
      type: { default: 'add' }
    },
    data(){
      let checkCommission = (rule, value, callback) => {
        if (value > this.formData.goodsCommission) {
          callback(new Error('不可超过商品佣金'));
        } else {
          callback()
        }
      };
      return {
        groupBookingTypeData:{
            'putong': '普通拼团',
            // 'laodaixin': '老带新拼团',
        },
        pickerOptions:{
          disabledDate: (time) => {
            // 如果函数里处理的数据比较麻烦,也可以单独放在一个函数里,避免data数据太臃肿
            return this.dealDisabledDate(time);
          }
        },
        pickerOptions2:{
          disabledDate: (time) => {
            // 如果函数里处理的数据比较麻烦,也可以单独放在一个函数里,避免data数据太臃肿
            return this.dealDisabledDate(time, true);
          }
        },
        pageTypes: [
            { name: '商品', val: 'GOODS'},
            { name: '套餐', val: 'PACKAGE'}
        ],    // 内页类型
        // 会员等级
        userLevels: ['普通用户', '兰蜜', '大区', '董事'],
        // 商品分类
        goodsCategory: [],

        durningDay: 1,
        durningHour: 0,
        durningMinute: 0,
        tempGoodsSelect: [],
        tempPackageSelect: [],
        setGoodsCategoryTemp: [],
        pageLoading: false,
        btnLoading: false,
        formData: {
          groupBookingType: 'putong',
          isOpenVirtualGroup: '1',
          alreadyGroupGoodsNum: 0,
          goodsId: '',
          goodsName: '',
          goodsPrice: '',
          goodsType: '',
          groupBuyStatus: 1, // 活动状态：1 生效中，2 已失效
          groupLimit: '', // 参团限制次数（空则表示不限制）
          groupNeedNum: '', // 参团人数
          groupPrice: '', // 拼团价格（元
          groupTime: 60 * 60 * 24, // 拼团有效期（秒）
          id: '',
          isTop: 1,
          promotionName: '',
          tempDateRange:[]
        },
        defaultStart: '',
        defaultStartHour: '',
        formRules: {
          commissionLimit:[
            {validator: checkCommission, trigger: 'change'},
            {pattern: regexp.zMoney, message: '大于等于0,最多保留两位小数', trigger: 'change'}
          ]
        }
      }
    },
    created(){
      this.fetchData();
      // this.fetchCategoryData();
    },
    watch: {
      $route() {
        this.fetchData()
      }
    },
    computed: {
      useGoodsType() {
        if(this.formData['BY_MODEL_TYPE'] || this.formData['BY_GOODS_TYPE']) {
          return 'by_goods_type'
        }
        if(this.formData['BY_GOODS'] || this.formData['BY_PACKAGE']) {
          return 'by_goods'
        }
        return ''
      }
    },
    methods: {
      getCurrentTime() {
        if(this.defaultStart){
          return
        }
        let time = new Date()
        const h = time.getHours()
        const m = time.getMinutes()
        const s = time.getSeconds()
        let res = h + ':' + m + ':' + s
        this.defaultStartHour = res
        this.defaultStart = time.getTime()
        // return res
      },
      setGroupTime() {
        const secNum = this.durningDay * 60 * 60 * 24 + this.durningHour * 60 * 60 + this.durningMinute * 60
        this.$set(this.formData, 'groupTime', secNum)
        console.log('this.formData.groupTime', this.formData.groupTime)
      },
      fetchData(){
        if(this.id){
          this.pageLoading = true;
          this.request({
            url: '/gb-manage/groupbuying/' + this.id,
            method: 'get',
            params: { if: this.id }
          }).then(({data}) => {
            if(!data.commission){
              data.commission = 0
            }
            let topValue = data.isTop
            data.isTop = JSON.stringify(topValue)
            this.formData = {
              ...data,
              tempDateRange: data.startTime ? [data.startTime, data.endTime]:[],
              groupBookingType: 'putong',
              isOpenVirtualGroup: data.isOpenVirtualGroup + ''
            };
            if (this.formData.groupTime) {
              const oneDay = 60 * 60 * 24
              const oneHour = 60 * 60
              const oneMinute = 60
              this.durningDay = Math.floor(this.formData.groupTime / oneDay)
              this.durningHour = Math.floor((this.formData.groupTime - (this.durningDay * oneDay)) / oneHour)
              this.durningMinute = Math.floor((this.formData.groupTime - (this.durningDay * oneDay) - (this.durningHour * oneHour)) / oneMinute)
            }
            if (this.formData.goodsName) {
              this.tempGoodsSelect = [{
                goods_id: this.formData.goodsId,
                pic: this.formData.goodsPic,
                title: this.formData.goodsName,
                marketValue: this.formData.goodsPrice,
                type: this.formData.goodsTyoe
              }]
            }
            this.getSkuNums()
            this.pageLoading = false;
            this.formData.commission = 0
          }).catch(err => {
            console.log(err);
            this.pageLoading = false;
          });
        }
      },
      chooseGoods(){
        let selected = [{
          goodsId: this.formData.goodsId,
          name: this.formData.goodsName,
          pic: this.formData.goodsPic,
          marketValue: this.formData.goodsPrice,
          type: this.formData.goodsTyoe
        }]
        this.goodsChoose({ count: 1, excludeCrush: 1 }, selected).then(val => {
          this.tempGoodsSelect = this.tempGoodsSelect.filter(item=>item.type===2).concat(val.map(async item => {
            // 检测互斥
            const param = {
              id: item.goodsId,
              checkList: [1, 2, 3, 4] // 互斥类型
            }
            const res = await goodsCheck(param)
            if (res.status !== 200) { return }
            this.formData.goodsId = item.goodsId
            this.formData.goodsPic = item.image
            this.formData.categoryName = item.parentCategoryName
            this.formData.categoryId = item.parentCategoryId
            this.formData.goodsCommission = item.maximumCommission
            this.formData.goodsName = item.name
            this.formData.promotionName = item.name
            this.formData.goodsPrice = item.marketValue
            this.formData.serialNo = item.serialNo
            this.formData.goodsType = 1
            this.getSkuNums()

            return {
                goods_id: item.goodsId,
                pic: item.image,
                title: item.name,
                subtitle: item.subName,
                marketValue: item.marketValue,
                goodsCommission: item.maximumCommission,
                price: item.price,
                type: 1,
                from_type: 1
              }
          }))
        })
      },
      getSkuNums() {
        if (!this.formData.serialNo) {
            return
          }
        //   console.log('this.formData', this.formData)
        // return
        if (this.formData.goodsType === 1) {
          let data = {
            serialNo: this.formData.serialNo,
            goodsName: '',
            organizationId: 1,
            pageIndex: 1,
            pageSize: 15,
            skuCode: '',
            goodsType: this.formData.goodsType
          };
          this.request({
            url: '/bsnl-product/goodssku/query',
            method: 'post',
            data
          }).then(({data, totalCount}) => {
            if(totalCount){
              this.$set(this.formData, 'distributableSkuNumber', data[0].distributableSkuNumber)
              this.$set(this.formData, 'goodsCommission', this.formData.goodsCommission)
            }
          }).catch(err => {
            this.$message.error('服务器异常');
          });
        } else {
          this.request({
            url: '/bsnl-product/package/details',
            method: 'get',
            params: {
              id: this.formData.serialNo
            }
          }).then(({data, totalCount}) => {
            let minNum = 0
            data.packageGoodsList.map(item=>{
              item.goodsAttr.map(subItem=>{
                if(minNum === 0) {
                  minNum = subItem.totalSkuNumber
                } else {
                  if(minNum > subItem.totalSkuNumber) {
                    minNum = subItem.totalSkuNumber
                  }
                }
              });
            });
            this.$set(this.formData, 'distributableSkuNumber', minNum)
            this.$set(this.formData, 'goodsCommission', data.packageRequest.maximumCommission)
          }).catch(err => {
            this.$message.error('服务器异常');
          });
        }

      },
      chooseGoodsPackage(){
        let selected = [{
          packageId: this.formData.goodsId,
          name: this.formData.goodsName,
          pic: this.formData.goodsPic,
          marketValue: this.formData.goodsPrice,
          type: this.formData.goodsTyoe
        }]
        this.packageChoose({ count: 1, excludeCrush: 1 }, selected).then(val => {
          this.tempGoodsSelect = this.tempGoodsSelect.filter(item=>item.type===1).concat(val.map(async item => {
            // 检测互斥
            const param = {
              id: item.packageId,
              checkList: [1, 2, 3, 4] // 互斥类型
            }
            const res = await goodsCheck(param)
            if (res.status !== 200) { return }
            this.formData.promotionName = item.name
            this.formData.serialNo = item.id
            this.formData.goodsId = item.packageId
            this.formData.goodsPic = item.image
            this.formData.goodsName = item.name
            this.formData.goodsPrice = item.marketValue
            this.formData.goodsType = 2
            this.getSkuNums()
            return {
              goods_id: item.packageId,
              pic: item.image,
              title: item.name,
              subtitle: item.subTitle,
              marketValue: item.marketValue,
              price: item.price,
              pack_type: item.type,
              type: 2,
              from_type: 3
            }
          }))
        });
      },
      removeTempSelect(item) {
        const _this = this
        this.$confirm(`确定要删除 ${item.goodsName} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$set(this.formData, 'goodsId', '')
          this.$set(this.formData, 'goodsName', '')
          this.$set(this.formData, 'goodsPrice', '')
          this.$set(this.formData, 'goodsType', '')
          this.$set(this.formData, 'promotionName', '')
          _this.tempGoodsSelect.splice(_this.tempGoodsSelect.indexOf(item), 1)
        }).catch(err => {
          console.log(err);
        });
      },
      removeTempPackageSelect(item) {
        const _this = this
        this.$confirm(`确定要删除 ${item.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempPackageSelect.splice(_this.tempPackageSelect.indexOf(item), 1)
          // _this.setPackageSelect()
        }).catch(err => {
          console.log(err);
        });
      },
      dealDisabledDate (time, type) {
        // time 是一个new Date数据
        if (type && this.formData.startTime) {
          return new Date(this.formData.startTime).getTime() > new Date(time).getTime() + 8.54e7
        }
        if(new Date(time).getTime() >= new Date().getTime() - 8.64e7){
                // return time.getTime() >= (new Date().getTime()) ;//时间范围必须是时间戳
            return false
        }else{
          if (type && this.formData.startTime) {
            return new Date(this.formData.startTime).getTime() > new Date(time).getTime()
          }
          return true
            // return time.getTime() < Date.now() - 2*8.64e7;//两天之内 根据自己需求来定
        }
      },
      save(){
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false
          }
          if (!this.formData.goodsId) {
            this.$message.warning('请选择商品');
            return
          }
          if (this.formData.groupTime < 2 * 60 * 60) {
            this.$message.warning('拼团有效期需大于两小时');
            return
          }
          // if (!this.formData.distributableSkuNumber) {
          //   this.$message.warning('商品库存为0, 请增加库存或选择其他商品')
          //   return
          // }
          if (this.formData.startTime > this.formData.endTime) {
            this.$message.warning('拼团生效结束时间需小于开始时间')
            return
          }
          // 如果所选时间小于当前时间
          const setTime = new Date(this.formData.startTime).getTime()
          let time = new Date()
          let currentT = time.getTime()
          if( currentT > setTime && !this.id) {
            this.$message.warning('活动开始时间不能早于当前系统时间，请重新设置')
            return
          }
          if(this.formData.goodsCommission === '' || this.formData.goodsCommission === null){
            this.formData.goodsCommission = 0
          }
          if(this.formData.commission === '' || this.formData.commission === null){
            this.formData.commission = 0
          }
          if(this.formData.groupPrice === '' || this.formData.groupPrice === null){
            this.formData.groupPrice = 0
          }
          this.btnLoading = true;
          // if(this.formData.tempDateRange.length){
          //   this.formData.startTime = this.formData.tempDateRange[0];
          //   this.formData.endTime = this.formData.tempDateRange[1];
          // }
          this.formData.commission = 0
          this.request({
            url: '/gb-manage/groupbuying',
            method: this.id ? 'put' : 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('保存成功');
            this.$router.push({name: 'groupBooking'});
          }).catch(err => {
            console.error(err);
            this.btnLoading = false;
          });
        });
      }
    }
  }
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .el-form-item .el-form-item {
      padding-bottom: 30px;
    }
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;

        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }

    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin: 0 0 20px 150px;
    }
    .groupBooking_goods{
      .el-select,.el-input{
        width: 100px;
      }
    }
    .limit_el-form{
      .el-input{
        width: 150px;
      }
    }
    .dateSelectDive{
      .el-select,.el-input{
        width: 100px;
      }
    }
</style>
